import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Iterator;
import javax.xml.stream.*;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
import java.util.*;
import java.net.MalformedURLException; 
import java.net.URL;
 
public class ParseXML {
  
    public URL url;
	
	public ParseXML(double lat, double lng) { 
		try { 
			this.url = new URL("http://maps.googleapis.com/maps/api/geocode/xml?address="+Double.toString(lat)+"%20"+Double.toString(lng));	
		} catch (MalformedURLException e) { 
				throw new RuntimeException(e); 
		} 
    } 
	
	
	public InputStream entrada() { 
		try { 
			return url.openStream(); 
		} catch (Exception e) { 
				throw new RuntimeException(e); 
		} 
    } 
	
	public String obtenerCiudad() throws Exception{
     try{	 
	   XMLInputFactory inputFactory = XMLInputFactory.newInstance();
		InputStream in = entrada();
		
	    XMLEventReader eventReader = inputFactory.createXMLEventReader(in);
		
		Boolean area = false;
		String ciudad = "";
 
		while (eventReader.hasNext() && area == false) {
			XMLEvent evento = eventReader.nextEvent();
 
			if (evento.isStartElement()) {
 
				StartElement startElement = evento.asStartElement();
 
				if (evento.isStartElement()) {
					if (evento.asStartElement().getName().getLocalPart().equals("type")) {
						evento = eventReader.nextEvent();
 
						if(evento.asCharacters().getData().equals("administrative_area_level_1")){
							area = true;
						}
 
					}
				}
				
				if (evento.isStartElement()) {
					if (evento.asStartElement().getName().getLocalPart().equals("short_name")) {
						evento = eventReader.nextEvent();
					    ciudad = evento.asCharacters().getData();
					}
				}
			}		
		}
		return ciudad;
	  }
	   catch(Exception e){
		  throw new Exception(e); 
	  }
	}
   
}